<?php

namespace backend\controllers;

use Yii;
use backend\models\Goods;
use backend\models\GoodsForm;
use backend\models\GoodsClass;
use backend\models\User;
use backend\models\UploadForm;
use backend\models\Logs;
use backend\models\SendEmail;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\Json;

/**
 * GoodsController implements the CRUD actions for Goods model.
 */
class GoodsController extends Controller
{
    private $allStatus=[];
    private $classes=[];
    private $yylist=[];

    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],

            'access'=>[
                'class'=> \backend\components\PermissionBehavior::className(),

            ],


        ];
    }
    public function beforeAction($action)
    {

        if (Yii::$app->user->isGuest) {

            header("location:/site/login");
            exit;

        }
        $goodsclass = new GoodsClass();

//         $gyslist = User::find()->leftjoin('auth_assignment','auth_assignment.user_id=user.id')->where('auth_assignment.item_name="供应商"')->select("user.id,user.realname")->all();
       $gyslist=$this->getmygys();
        $classlist = $goodsclass->find()->select('id,classname')->all();
        $yylists=User::find()->leftjoin('auth_assignment','auth_assignment.user_id=user.id')->where('auth_assignment.item_name="一级审批人"')->select("user.id,user.realname")->all();

        $allStatus = $classes = $yylist = [0=>'请选择'];
        foreach($gyslist as $item){
            $allStatus[$item->id] = $item->realname;
        }
        foreach($classlist as $item){
            $classes[$item->id] = $item->classname;
        }
        foreach($yylists as $item){
            $yylist[$item->id] = $item->realname;
        }


        $this->allStatus=$allStatus;


        $this->classes=$classes;


        $this->yylist = $yylist;

        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }
    public  function getmygys(){
        $role = User::getmyrole();
        $userid=Yii::$app->user->id;

        if($role=='供应商'){
            return [];

        }elseif($role=='一级审批人'){

            $gyss=Goods::find()->where(['nextid'=>$userid])->groupBy('gys')->select('gys')->all();

            $mygys=[];
            foreach($gyss as $gys){
                $mygys[]=$gys->gys;
            }
            return User::find()->where(['in','id',implode(",",$mygys)])->all();
        }else{
            return User::find()->leftjoin('auth_assignment','auth_assignment.user_id=user.id')->where('auth_assignment.item_name="供应商"')->select("user.id,user.realname")->all();
        }
    }
    /**
     * Lists all Goods models.
     * @return mixed
     */
    public function actionIndex()
    {
        $model = new UploadForm();
        $searchModel = new GoodsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        $goodssearch=[];
        if(!empty(Yii::$app->request->queryParams) && isset(Yii::$app->request->queryParams['GoodsSearch'])){
            $goodssearch = Yii::$app->request->queryParams['GoodsSearch'];
        }




        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'allStatus' => $this->allStatus,


            'classes' => $this->classes,

            'yylist'=>$this->yylist,

            'model'=>$model,
            'goodssearch'=>$goodssearch
        ]);
    }

    /**
     * Displays a single Goods model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    public function actionLogsview($id){
        return $this->redirect('/logs/index?gid='.$id);
    }
    /**
     * Creates a new Goods model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $this->layout=false;
        $remark='';
        $goodsform = new GoodsForm();
        $model = new Goods();

        $model->createtime = date("Y-m-d H:i:s");
        $model->updatetime = date("Y-m-d H:i:s");

        if(Yii::$app->request->isPost ){


            $post = Yii::$app->request->post('Goods');
            $data = array_merge(Yii::$app->request->post(),['GoodsForm'=>$post]);
            $goodsform->load($data);
            $goodsform->gys=Yii::$app->user->id;
            $goodsform->createtime = date("Y-m-d H:i:s");
            $goodsform->updatetime = date("Y-m-d H:i:s");
//            var_dump($goodsform,Yii::$app->request->post());
            if(!$goodsform->validate()){
                $info='';
                foreach($goodsform->getErrors() as $key=>$item){
                    $info .=$item[0].'<br>';
                }
                Yii::$app->session->setFlash('error', $info);
                return $this->redirect('/goods/index');
            }
            $model->load(Yii::$app->request->post());
            $model->gys=Yii::$app->user->id;



            if(empty($post['class'])){
                Yii::$app->session->setFlash('error', '类别必选');
                return $this->redirect('/goods/index');
            }
            if(empty($post['nextid'])){
                Yii::$app->session->setFlash('error', '运营必选');
                return $this->redirect('/goods/index');
            }
            //查找是否以前有过
            $goods = new Goods();
            $good = $goods->find()->where(['goodsid'=>$post['goodsid']])->orWhere(['goodsno'=>$post['goodsno']])->one();

            if(!empty($good)){//以前有过需要对比


                Yii::$app->session->setFlash('error', 'SKU重复，或者货品编号重复，请直接更新数据！<a href="javascript:edit('.$good->id.')">点这里去更新</a>');

                return $this->redirect('/goods/index');


            }else{//新商品
                $model->check=3;
                $model->lastprice=$model->inprice;
                $model->upfee=0;
                $oprtype = "创建商品";
                $remark=$post['goodsname'];
                $model->progress=Json::encode([

                    ['status'=>'审核通过', 'opr'=>'系统','oprtime'=>date('Y-m-d H:i:s')]

                ]);
            }

        }else{//表单默认空
            $model->check=0;
        }

        $model->export=false;
        if (Yii::$app->request->isPost && $model->save()) {
            //日志
            $logs = new Logs();
            $logs->goodsid = $model->id;
            $logs->opid = Yii::$app->user->id;
            $logs->oprtype = $oprtype;
            $logs->remark = $remark;
            $logs->oprtime = date('Y-m-d H:i:s');

            $logs->save();
            $yunying = User::findOne($model->nextid);


            //邮件
            $sendmail=new SendEmail();

            $price=$model->priceunit ? '$'.$model->inprice :  '￥'.$model->inprice;

            $sendmail->name='供货价管理系统';
            $sendmail->email=Yii::$app->params['adminEmail'];
            $sendmail->subject=Yii::$app->user->identity->realname.'创建1个新商品';
            $sendmail->body=Yii::$app->user->identity->realname."创建1个新商品.<br/>货品编号：".$model->goodsno." 品名：<a href=".Yii::$app->params['domainName']."'/goods/view?id={$model->id}'>{$model->goodsname}</a> 供货价：".$price;
            $yyname = $yunying->realname ? $yunying->realname:$yunying->username;
            if ($sendmail->sendEmail($yunying->email)) {

                Yii::$app->session->setFlash('success', '给运营'.$yyname.'的邮件已发送成功！');


            } else {
                Yii::$app->session->setFlash('success', '给运营'.$yyname.'的邮件已发送失败,请其他方式通知对方！');

            }

            return $this->redirect(['view', 'id' => $model->id]);
        }
        $needSelected=Yii::$app->user->id;
        return $this->render('create', [
            'model' => $model,
            'allStatus' => $this->allStatus,
            'needSelected' => $needSelected,
            'unitcheck'=>0,
            'classes' => $this->classes,
            'classcheck' => 0,
            'yylist'=>$this->yylist,
            'myyy'=>0

        ]);
    }

    /**
     * Updates an existing Goods model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $this->layout=false;
        $goodsform = new GoodsForm();
            $model=$this->findModel($id);
        $remark='';

        if( Yii::$app->request->isPost){
            $post = Yii::$app->request->post('Goods');
             $data = array_merge(Yii::$app->request->post(),['GoodsForm'=>$post]);
            $goodsform->load($data);
//            var_dump($goodsform,Yii::$app->request->post( ));exit;
            $goodsform->gys = $model->gys;
            $goodsform->createtime = $model->createtime;
            $goodsform->updatetime = date("Y-m-d H:i:s");

            if(!$goodsform->validate()){
                $info='';
                foreach($goodsform->getErrors() as $key=>$item){
                    $info .=$item[0].'<br>';
                }
                Yii::$app->session->setFlash('error', $info);
                return $this->redirect('/goods/index');
            }
            if(empty($post['class'])){
                Yii::$app->session->setFlash('error', '类别必选');
                return $this->redirect('/goods/index');
            }
            if(empty($post['nextid'])){
                Yii::$app->session->setFlash('error', '运营必选');
                return $this->redirect('/goods/index');
            }
            if($model->check!=3 && $model->check!=4){//

                Yii::$app->session->setFlash('error', '审核中不允许修改！');
                return $this->redirect('/goods/index');
            }
            if($model->goodsid != $post['goodsid'] ){

                $remark .='更改SKU（'.$model->goodsid.' to '.$post['goodsid'].'） ';
                $model->goodsid = $post['goodsid'];
            }
            if($model->goodsno != $post['goodsno'] ){

                $remark .='更改货品编号（'.$model->goodsno.' to '.$post['goodsno'].'） ';
                $model->goodsno = $post['goodsno'];
            }
            if($model->nextid != $post['nextid'] ){

                $remark .='更改运营商（'.$model->nextid.' to '.$post['nextid'].'） ';
                $model->nextid = $post['nextid'];
            }
            if($model->goodsname != $post['goodsname'] ){

                $remark .='更改商品名称（'.$model->goodsname.' to '.$post['goodsname'].'） ';
                $model->goodsname = $post['goodsname'];
            }
            if($model->class != $post['class'] ){

                $remark .='更改商品分类（'.$model->class.' to '.$post['class'].'） ';
                $model->class = $post['class'];
            }

            $price_remark='';
            if($model->inprice != $post['inprice'] ){

                $unit = $model->priceunit ? "$":"￥";
                $newunit =  $post['priceunit'] ? "$":"￥";
                $oldprice = (string)$model->lastprice;
                $oldupfee = (string)$model->upfee;
                $newprice = $post['inprice'];

                $model->inprice = $newprice;
                $model->upfee = (string)(Yii::$app->formatter->asDecimal(($newprice-$oldprice)/$oldprice, 4) * 100 );
                if($oldprice >= $newprice){//旧价格大于等于现在价格（降价或原价）直接免审核
                    $model->check=3;
                    $remark .='更改审核状态为审核通过 ';
//                    $progress=Json::decode($model->progress);
                    $new_progress=[['status'=>'审核通过', 'opr'=>'系统','oprtime'=>date('Y-m-d H:i:s')]];
                    $model->progress=Json::encode($new_progress);
                    $model->lastprice = $newprice;


                    $price_remark='<span style="color:green">'.$unit.$oldprice.'↘'.$newunit.$newprice.'</span><br>';
                    $price_remark.='<span style="color:green">'.$oldupfee.'%↘'.$model->upfee.'%</span>';
                }else{//需要审核,先保存上次价格
                    $model->check=0;
                    $remark .='更改审核状态为待审核 ';

                    $price_remark='<span style="color:red">'.$unit.$oldprice.'↗'.$newunit.$newprice.'</span><br>';
                    $price_remark.='<span style="color:red">'.$oldupfee.'%↗'.$model->upfee.'%</span>';
                    $new_progress=[['status'=>'待审核', 'opr'=>Yii::$app->user->identity->realname,'oprtime'=>date('Y-m-d H:i:s')]];
                    $model->progress=Json::encode($new_progress);

                }



                if($newprice!=$oldprice ){
                    $remark .='更改价格（'.$unit.$oldprice.' to '.$newunit.$newprice.'） ';
                    $remark .='更改上次价格（'.$unit.$oldprice.' to '.$newunit.$newprice.'） ';
                    $remark .='更改涨幅（'.$oldupfee.'% to '.$model->upfee.'%） ';



                }

            }

            if($model->remark != $post['remark'] ){

                $remark .='更改备注（'.$model->remark.' to '.$post['remark'].'） ';
                $model->remark = $post['remark'];
            }
            if($model->priceunit != $post['priceunit'] ){

                $remark .='更改币种（'.$model->priceunit.' to '.$post['priceunit'].'） ';
                $model->priceunit = $post['priceunit'];
            }
            $model->export=0;
            $remark .='更改为未导出状态';

            $model->updatetime = date('Y-m-d H:i:s');


        }

        if (Yii::$app->request->isPost && $model->save()) {
            if(!empty($remark)){
                $logs = new Logs();
                $logs->goodsid = $model->id;
                $logs->opid = Yii::$app->user->id;
                $logs->oprtype = '更新商品';
                $logs->remark = $remark;
                $logs->price_remark=$price_remark;
                $logs->oprtime = date('Y-m-d H:i:s');

                $logs->save();
            }

            Yii::$app->session->setFlash('success', '更新成功');
            return $this->redirect(['view', 'id' => $model->id]);
        }else{
            $info='';
            foreach($model->getErrors() as $key=>$item){
                $info .=$item[0].'<br>';
            }
            if(!empty($info)){
                Yii::$app->session->setFlash('error', $info);
            }



        }

        return $this->render('update', [
            'model' => $model,
            'allStatus' => $this->allStatus,
            'needSelected' => $model->gys,
            'unitcheck'=>$model->priceunit,
            'classes' => $this->classes,
            'classcheck' => $model->class,
            'yylist'=>$this->yylist,
            'myyy'=>$model->nextid
        ]);
    }

    /**
     * Check an existing Goods model.
     * If Check is successful, the browser will be redirected to the 'index' page.
     * @param integer $id,integer $check
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionCheck($id,$ischeck,$reason=''){
        if(mb_strlen($reason)>50){
            Yii::$app->session->setFlash('error', '备注不能超过50个字！');
            return $this->redirect(Yii::$app->request->referrer);
        }
        $u = new User();
        $myrole=$u->getmyrole();
       if(strpos($id,",")!==false){
        $id = explode(",",$id);
        $goods = $this->findModels($id);
        $opr=0;

        foreach($goods as $good){
            if($good->check==4 || $good->check==3){ //不通过的和三审通过的不允许批量审核
                continue;
            }
            if(($myrole=='一级审批人' && $good->check==0) || ($myrole=='二级审批人' && $good->check==1) || ($myrole=='三级审批人' && $good->check==2)){


            } else{
                continue;
            }
            if($ischeck==0){

                $remark = ($good->check+1).'审不通过';
                $good->check=4;
                $oprtype='审核不通过';
            }else{
                $good->check++;
                $oprtype='审核通过';

                $remark=$good->check.'审通过';
                if($good->check==3){
                    $unit = $good->priceunit ? "$":"￥";
                    $remark .='更改上次价格（'.$unit . $good->lastprice.' to '.$unit . $good->inprice.'） ';
                    $good->lastprice=$good->inprice;
                }

            }
            if($good->progress){
                $progress=Json::decode($good->progress);
                $new_progress=[['status'=>$remark, 'opr'=>Yii::$app->user->identity->realname,'oprtime'=>date('Y-m-d H:i:s')]];
                $good->progress=Json::encode(array_merge($progress,$new_progress));
            }

            $good->save();
            $logs = new Logs();
            $logs->goodsid = $good->id;
            $logs->opid = Yii::$app->user->id;
            $logs->oprtype = $oprtype;
            $logs->remark = $remark;
            $logs->oprtime = date('Y-m-d H:i:s');

            $logs->save();
            $opr++;
        }
        if(count($goods) == $opr){
            Yii::$app->session->setFlash('success', '操作成功！');
            return 1;
        }else{
            Yii::$app->session->setFlash('error', '部分商品跳过审核（可能勾选了审核过的数据或者暂时不该由您审核的数据）！');
            return 0;
        }

       }else{

           $good = $this->findModel($id);
           if($good->check==4 || $good->check==3){ //不通过的和三审通过的不允许批量审核
               Yii::$app->session->setFlash('error', '本商品审核过了，无须再审！');
              return $this->redirect(['index']);
           }
           if(($myrole=='一级审批人' && $good->check==0) || ($myrole=='二级审批人' && $good->check==1) || ($myrole=='三级审批人' && $good->check==2)){
               $oprtype=$remark='';
               if($ischeck==0){
                   $remark = ($good->check+1).'审不通过';
                   $good->check=4;
                   $oprtype='审核不通过';
               }else{
                   $good->check++;
                   $oprtype='审核通过';

                   $remark=$good->check.'审通过';
                   if($good->check==3){

                       $remark .='更改上次价格（'.$good->lastprice.' to '.$good->inprice.'） ';
                       $good->lastprice=$good->inprice;
                   }

               }
               //如果有审核原因，保存到这里
               if(!empty($reason)){
                   $remark.=",".$reason;
               }
               if($good->progress){
                   $progress=Json::decode($good->progress);
                   $new_progress=[['status'=>$remark, 'opr'=>Yii::$app->user->identity->realname,'oprtime'=>date('Y-m-d H:i:s')]];
                   $good->progress=Json::encode(array_merge($progress,$new_progress));
               }

               $good->save();

               $logs = new Logs();
               $logs->goodsid = $id;
               $logs->opid = Yii::$app->user->id;
               $logs->oprtype = $oprtype;
               $logs->remark = $remark;
               $logs->oprtime = date('Y-m-d H:i:s');

               $logs->save();
               return $this->redirect(['index']);

           }  else{
               Yii::$app->session->setFlash('error', '本条数据暂时不能由您审核');
               return $this->redirect(['index']);
           }

       }

    }
    /**
     * Finds the Goods model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Goods the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Goods::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('所选商品不存在！');
    }
    protected function findModels($ids)
    {
        if (count($model = Goods::find()->where(['in','id',$ids])->all()) != 0 ) {
            return $model;
        }

        throw new NotFoundHttpException('所选商品有不存在的！');
    }

    //一审二审往后报告
    public function actionReport(){
        //一审二审往后报告
        $userid = Yii::$app->user->id;
        $touserid = Yii::$app->user->identity->parentid;
//        $myname = Yii::$app->user->identity->realname ? Yii::$app->user->identity->realname : Yii::$app->user->identity->username;
        if($touserid){//一级二级都有parentid
            $touser = User::findOne($touserid);

        }

        $logs = new Logs();
        $log = $logs->find()
            ->where(['opid'=>$userid])
            ->andWhere(['like','oprtype','审核通过'])
            ->andwhere(['>','oprtime',date('Y-m-d 00:00:00')])
            ->andwhere(['<','oprtime',date('Y-m-d 23:59:59')])
            ->count();
        if($log==0){
            Yii::$app->session->setFlash('error', '您今天没有审核，不能提交报告！');
            return $this->redirect('/goods/index');
            //echo "<script>alert('您今天没有审核，不能提交报告！');window.history.go(-1);</script>";

        }
        $report= $logs->find()
            ->where(['opid'=>$userid])
            ->andWhere(['oprtype'=>'审核报告'])
            ->andwhere(['>','oprtime',date('Y-m-d 00:00:00')])
            ->andwhere(['<','oprtime',date('Y-m-d 23:59:59')])
            ->count();
        if($report>0){
            Yii::$app->session->setFlash('error', '您今天已经提交过报告，无须多次提交！');
            return $this->redirect('/goods/index');
        }
        $role=User::getmyrole();
        if($role=='一级审批人'){
            $sendinfo='请前往供货价管理系统，筛选审核状态为一审通过商品进行审核';
            $model=new Logs();
            $model->opid=$userid;
            $model->oprtype='审核报告';
            $model->oprtime=date('Y-m-d H:i:s');
            $model->remark='给二级审核';
            $model->save();
        }else{
            $sendinfo='请前往供货价管理系统，筛选审核状态为二审通过商品进行审核';
            $model=new Logs();
            $model->opid=$userid;
            $model->oprtype='审核报告';
            $model->oprtime=date('Y-m-d H:i:s');
            $model->remark='给三级审核';
            $model->save();
        }

//        foreach($log as $key => $item){
//            $good = Goods::findOne($item->goodsid);
//            $sendinfo.=($key+1).'、《'.$good->goodsname.'》'.$item->remark.' '.$item->oprtime.'<br>';
//        }
        $this->sendmail($touser->email,"有".$log."个商品需要审核",$sendinfo);
       // echo "<script>alert('操作成功！');window.location.href='/goods/index';</script>";
        Yii::$app->session->setFlash('success', '操作成功！');
        return $this->redirect('/goods/index');
    }
    public function actionNotice(){
        //三审通知
        $userid = Yii::$app->user->id;
        $childs = User::find()->where(['parentid'=>$userid])->all();
        $myname = Yii::$app->user->identity->realname ? Yii::$app->user->identity->realname : Yii::$app->user->identity->username;
        $notice_user=[];
        foreach($childs as $child){
            $childid = $child->id;
            $notice_user[]=$child;
            $grandsons = User::find()->where(['parentid'=>$childid])->all();
            foreach($grandsons as $grandson){

                $notice_user[]=$grandson;
            }
        }
        $gyslist=[];//收到通知的供应商列表

        $logs = new Logs();
        $log_pass = $logs->find()
            ->where(['opid'=>$userid])
            ->andWhere(['like','remark','3审通过'])
            ->andwhere(['>','oprtime',date('Y-m-d 00:00:00')])
            ->andwhere(['<','oprtime',date('Y-m-d 23:59:59')])
            ->all();
        $log_dis = $logs->find()
            ->where(['opid'=>$userid])
            ->andWhere(['like','remark','3审不通过'])
            ->andwhere(['>','oprtime',date('Y-m-d 00:00:00')])
            ->andwhere(['<','oprtime',date('Y-m-d 23:59:59')])
            ->all();
        if(count($log_pass)+count($log_dis)==0){
//            echo "<script>alert('您今天没有审核，不能提交通知！');window.history.go(-1);</script>";exit;
            Yii::$app->session->setFlash('error', '您今天没有审核，不能提交通知！');
            return $this->redirect('/goods/index');
        }
        $report= $logs->find()
            ->where(['opid'=>$userid])
            ->andWhere(['oprtype'=>'审核通知'])
            ->andwhere(['>','oprtime',date('Y-m-d 00:00:00')])
            ->andwhere(['<','oprtime',date('Y-m-d 23:59:59')])
            ->count();
        if($report>0){
            Yii::$app->session->setFlash('error', '您今天已经提交过通知，无须多次提交！');
            return $this->redirect('/goods/index');
        }
        $model=new Logs();
        $model->opid=$userid;
        $model->oprtype='审核通知';
        $model->oprtime=date('Y-m-d H:i:s');
        $model->remark='给一级和二级审核邮件，给供应商短信';
        $model->save();
        $sendinfo=$myname.'已审核'.(count($log_pass)+count($log_dis)).'个商品，'.count($log_pass).'个审核通过，'.count($log_dis).'个审核不通过<br>';
        $sendinfo.="审核通过：<br>";
        foreach($log_pass as $key => $item){
            $good = Goods::findOne($item->goodsid);
            if(!array_key_exists($good->gys,$gyslist)){
                $gys=User::findOne($good->gys);
                $gyslist[$good->gys]['telphone']=$gys->telphone;
                $gyslist[$good->gys]['total']=0;
            }
            $gyslist[(string)$good->gys]['total']++;
            $sendinfo.=($key+1).'、货品编号：'.$good->goodsno.' 品名：'.$good->goodsname.' 供货价：'.$good->inprice.'<br>';
        }
        $sendinfo.="审核不通过：<br>";
        foreach($log_dis as $key => $item){
            $good = Goods::findOne($item->goodsid);
            if(!array_key_exists($good->gys,$gyslist)){
                $gys=User::findOne($good->gys);

                $gyslist[$good->gys]['telphone']=$gys->telphone;
                $gyslist[$good->gys]['total']=0;
            }
            $gyslist[(string)$good->gys]['total']++;
            $remark=$item->remark;
            if(strpos(",",$remark)){
                $remark=explode(",",$remark)[1];
            }
            $sendinfo.=($key+1).'、货品编号：'.$good->goodsno.' 品名：'.$good->goodsname.' 供货价：'.$good->inprice.' 备注：'.$remark.'<br>';
        }
        //给二级和三级审核发邮件
        foreach($notice_user as $u){
            $this->sendmail($u->email,$myname."已审核商品",$sendinfo);
        }
        //给供应商发短信


       $result= $this->sendsms($gyslist);
//exit;
        if($result===false){
            return $this->redirect('/goods/index');
        }else{
            Yii::$app->session->setFlash('success', '操作成功');
            return $this->redirect('/goods/index');
        }

    }
    public function sendsms($gyslist){

        $url="http://TSN19.800CT.COM:8901/MWGate/wmgw.asmx/MongateSendSubmit";//61.145.229.28:8806
        foreach($gyslist as $key=>$gys){
            if(!empty($gys['telphone'])){
                $arr = array(
                    'userId'=>'JJ1213',//J92599
                    'password'=>'768293',//688963
                    'pszMobis'=>$gys['telphone'],
                    'pszMsg'=>'您在供货价审批系统创建的'.$gys['total'].'个商品已审核完成，详情请登录查看',
                    'iMobiCount'=>1,
                    'pszSubPort'=>'0001',
                    'MsgId'=>'',
                );
                $result= $this->doCurlPostRequest($url,http_build_query($arr));
//                var_dump($arr,$result);
            }


        }
        return true;
//    return $result;
//        $client=new \SoapClient('http://61.145.229.28:8806/MWGate/wmgw.asmx?wsdl');
//        return $client->MongateSendSubmit('J92599','688963',implode(',',$gys_phones),$contents,count($gyslist),'*','');

    }
    public function sendmail($to,$subject,$content){


        return Yii::$app
            ->mailer
            ->compose()
            ->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name . ''])
            ->setTo($to)
            ->setSubject($subject)
            ->setHtmlBody($content)

            ->send();

    }
    /**
     ** @desc 封装 curl 的调用接口，post的请求方式
     **/
    function doCurlPostRequest($url,$requestString,$timeout = 5){
        if($url == '' || $requestString == '' || $timeout <=0){
            return false;
        }
        $con = curl_init((string)$url);
        curl_setopt($con, CURLOPT_HEADER, false);
        curl_setopt($con, CURLOPT_POSTFIELDS, $requestString);
        curl_setopt($con, CURLOPT_POST,true);
        curl_setopt($con, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($con, CURLOPT_TIMEOUT,(int)$timeout);
        return curl_exec($con);
    }

    function xml2array($xmlstring){
        $object = simplexml_load_string($xmlstring, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS);

        return @json_decode(@json_encode($object),1);

            //禁止引用外部xml实体
//            libxml_disable_entity_loader(true);
//            $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
//            return $values;


    }
    //读取商品信息准备审核
    public function actionReadcheck($id){
       $this->layout=false;
        return $this->render('readcheck', [
            'model' => $this->findModel($id),
        ]);
    }
    /**
     * Show an existing Goods progress.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionProgress($id){
        $this->layout=false;
        return $this->render('progress',[
            'progress'=>$this->findModel($id)->progress,
        ]);

    }
}
